package com.gyms.activity;

import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.classic.okhttp.beans.HVCitiesBean;
import com.classic.okhttp.services.ICommonService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyms.R;
import com.gyms.adapter.CityAdapter;
import com.gyms.base.BaseActivity;
import com.gyms.constant.Constants;
import com.gyms.manager.LocationManger;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cache.ACache;
import constant.EventConstant;
import constant.FileConstant;
import utils.FileUtils;
import utils.ScreenUtils;
import utils.SizeUtils;
import weight.MyGridView;
import weight.UiEvent;


/**
 * 城市列表
 * ltx
 */

public class CityActivity extends BaseActivity {
    @BindView(R.id.gv_city)
    MyGridView mGvCity;
    @BindView(R.id.tv_l_city)
    TextView mTvLCity;//定位城市
    @BindView(R.id.iv_back)
    ImageView mIvBack;

    private int singleSize;//单个城市选项的大小


    private ArrayList<HVCitiesBean> mHVCitiesBeens=new ArrayList<>();//城市列表数据源

    private CityAdapter mCityAdapter;
    private File file,mCurrCity;
    private Gson mGson;

    private LocationManger mLocationManger;



    @Override
    protected int getLayoutResId() {
        return R.layout.activity_city;
    }

    @Override
    protected void initView() {
        setTitle("选择城市");
        mIvBack.setImageResource(R.drawable.city_close_selector);
        mIvBack.setVisibility(View.VISIBLE);
        mCityAdapter = new CityAdapter(getApplicationContext());
        mGvCity.setAdapter(mCityAdapter);

        measureDistace();
        ViewGroup.LayoutParams lp = mTvLCity.getLayoutParams();
        lp.width = singleSize;
        lp.height = SizeUtils.dp2px(getApplicationContext(), 35);
        mTvLCity.setLayoutParams(lp);
        mLocationManger=LocationManger.getInstance(getApplicationContext());//初始化定位的manger
        mTvLCity.setText(mLocationManger.getLocationCity());//获取定位城市
    }

    @Override
    protected void setListener() {
        mGvCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mLocationManger.setCurCityBean(mHVCitiesBeens.get(position));//设置当前的cityBean
                EventBus.getDefault().post(new UiEvent(EventConstant.S_CITY, null));
                mMyApplication.mHVCitiesBean=mHVCitiesBeens.get(position);
                FileUtils.writeFileFromString(mCurrCity, mGson.toJson(mHVCitiesBeens.get(position)), false);//将城市数据写入文件
                onBackPressed();
            }
        });
    }

    @Override
    protected void processLogic() {
        mGson=new Gson();
        file = new File(Environment.getExternalStorageDirectory(), FileConstant.FILE_CITY);
        mCurrCity = new File(Environment.getExternalStorageDirectory(), FileConstant.FILE_SELCT_CITY);//当前选择城市的存储file
        getLocalCity();

        if(null==mHVCitiesBeens||mHVCitiesBeens.size()==0){//本地的数据不为0 就直接更新数据
            getCityData();
       }else
            notifyAdapter();

    }

    /**
     * 获取本地数据
     */

    private void getLocalCity() {
       /* String strCityList = FileUtils.readFile2String(file, FileConstant.CHARSET_NAME);*/
        String strCityList=ACache.get(mContext).getAsString(Constants.ALL_CITY_BEANS);
        mHVCitiesBeens = mGson.fromJson(strCityList, new TypeToken<List<HVCitiesBean>>() {
        }.getType());
        mHVCitiesBeens=mHVCitiesBeens==null?new ArrayList<HVCitiesBean>():mHVCitiesBeens;
    }

    /**
     * 获取城市列表
     */

    private void getCityData() {
        ICommonService.getCities(this, true, new ObjectCallback<ArrayList<HVCitiesBean>>() {
            @Override
            public void onSuccess(ArrayList<HVCitiesBean> response, String message) {
                if(null!=response&&response.size()!=0){
                    mHVCitiesBeens.addAll(response);
                    notifyAdapter();
                    mLocationManger.setHVCitiesBeens(mHVCitiesBeens);
                    ACache.get(mContext).put(Constants.ALL_CITY_BEANS,mGson.toJson(mHVCitiesBeens),ACache.TIME_DAY);//存一天
                    FileUtils.writeFileFromString(file, mGson.toJson(mHVCitiesBeens), false);//将城市数据写入文件
                }
            }

            @Override
            public void onErrorT(int code, ArrayList<HVCitiesBean> response, String errorMessage) {
                Logger.e("errorMessage");

            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                Logger.e("statusCode");
            }
        });

    }

    /**
     * 更新适配器
     */

    private void notifyAdapter() {
        mCityAdapter.setHVCitiesBeens(mHVCitiesBeens);
        mCityAdapter.notifyDataSetChanged();
    }

    /**
     * 测量单个distance
     */
    private void measureDistace() {
        singleSize = ( ScreenUtils.getScreenWidth(this)- SizeUtils.dp2px(mContext, 52)) / 3;
    }


    @OnClick(R.id.tv_l_city)
    public void onLocationClick() {
        mLocationManger.setLocationCityBean();
        EventBus.getDefault().post(new UiEvent(EventConstant.S_CITY, null));
        onBackPressed();
    }


    @OnClick(R.id.iv_back)
    public void onClickBack() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_close_in, R.anim.activity_close_out);
    }
}
